<template>
  <el-dialog
    ref="resourceCodeLabelRef"
    v-dialogDrag
    :append-to-body="true"
    :modal-append-to-body="true"
    :modal="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="选择绑定签码数据"
    class="pms-zr-dialog"
    v-bind="$attrs"
    v-on="$listeners"
    width="70%"
    @close="()=>{cancel()}"
  >
    <el-form ref="form" :model="form" label-width="160px" size="mini" :inline="true" style="margin-bottom: 10px;">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="资源资产编码" style="width: 100%;display: flex;">
            <el-input v-model="form.sourceAssetCode" class="pms-zr-input" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签ID" style="width: 100%;display: flex;">
            <el-input v-model="form.labelId" class="pms-zr-input" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否已绑定" style="width: 100%;display: flex;">
            <el-select v-model="form.isBind" placeholder="请选择" clearable :popper-append-to-body="false">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: right;padding-top: 5px">
          <el-button size="mini" class="pms-zr-button-primary" @click="doSearch" style="background: #eb4b4b !important;color: #FFF !important;">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div style="font-weight: bold;padding-bottom: 10px;color: #333333">有标签ID物资</div>
    <el-table
      ref="multipleTable"
      :data="tableDataTemp"
      max-height="400px"
      border
      row-key="sourceAssetCode"
      style="width: 100%;"
      :header-cell-style="{
        background: '#F5F5F5',
        color: '#333333',
        fontWeight:500
      }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column :selectable="({select})=> select" :reserve-selection="true" type="selection" width="55" />
      <el-table-column align="center" prop="sourceAssetCode" label="资源资产编码" />
      <el-table-column align="center" prop="labelId" label="标签ID" />
      <el-table-column align="center" prop="prjCode" label="已绑定的单项工程编码" />
    </el-table>
    <div v-if="showNoLabel">
      <div style="font-weight: bold;padding: 20px 0 10px;color: #333333">无标签ID物资</div>
      <div style="display: flex">
          <div style="width: 80px">绑定数量：</div>
          <el-input
              style="width: 150px"
              v-model="bindNum"
              type="number"
              class="pms-custom"
          />
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button class="pms-zr-button-primary" size="small" @click="save" style="background: #eb4b4b !important;color: #FFF !important;">确 定</el-button>
      <el-button class="pms-zr-button-primary" size="small" @click="cancel" style="margin-left: 10px !important;background: #eb4b4b !important;color: #FFF !important;">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import {checkMateLabelPrecision, filterAssetLabelList} from "@/api/acceptanceManagement/materialServiceBind";
import {msgInfoEl} from "@/utils";

export default {
    name: 'ResourceCodeLabel',
    components: {},
    props: {
        tableData:{
          type: Array,
          default: () => []
        },
        multipleData:{
          type: Array,
          default: () => []
        },
        selectItem:{
          type: Object,
          default: () => ({})
        },
        osAmount:{
            type: String,
        }
    },
    data() {
        return {
            tableDataTemp: [],
            form: {
              sourceAssetCode: '',
              labelId: '',
              isBind: ''
            },
            multipleSelection: [],
            status:false,
            bindNum:'',
            showNoLabel:false
        }
    },
    created() {
        console.log(this.selectItem)
        this.tableDataTemp=this.tableData;
        this.multipleSelection=this.multipleData;
        this.showNoLabel=this.tableData.length !== +this.osAmount
        this.bindNum=this.selectItem.subBoundNum- this.getAmountSum(this.multipleData) === 0 ? '' : this.numSub(this.selectItem.subBoundNum,this.getAmountSum(this.multipleData));
        this.form={
          sourceAssetCode: '',
          labelId: '',
          isBind: ''
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.setSelection()
            this.dialogEl('resourceCodeLabelRef')
        })
    },
    methods: {
        getAmountSum(arr){
            let sum = 0
            if (arr && arr.length > 0) {
                arr.forEach((item) => {
                    sum = this.numAdd(sum, item.amount)
                })
            }
            return sum
        },
        // 相加避免精度问题
        numAdd(num1, num2) {
            let baseNum1, baseNum2
            try {
                baseNum1 = num1.toString().split('.')[1].length
            } catch (e) {
                baseNum1 = 0
            }
            try {
                baseNum2 = num2.toString().split('.')[1].length
            } catch (e) {
                baseNum2 = 0
            }
            const baseNum = Math.pow(10, Math.max(baseNum1, baseNum2))
            return (num1 * baseNum + num2 * baseNum) / baseNum
        },
        // 相减避免精度问题
        numSub(num1, num2) {
            let baseNum1, baseNum2
            try {
                baseNum1 = num1.toString().split('.')[1].length
            } catch (e) {
                baseNum1 = 0
            }
            try {
                baseNum2 = num2.toString().split('.')[1].length
            } catch (e) {
                baseNum2 = 0
            }
            const baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
            return Math.round(num1 * baseNum - num2 * baseNum) / baseNum;
        },
        setSelection() {
          this.$refs.multipleTable.clearSelection() // 清除所有选项
          this.tableDataTemp.forEach((row) => {
              const flag = this.multipleSelection.some(item => item.sourceAssetCode === row.sourceAssetCode)
              if (flag) {
                this.$refs.multipleTable.toggleRowSelection(row, true)
              }
          })
          this.status=true
        },
        cancel() {
          this.$emit('update:visible', false)
        },
        checkBindNumOne(){
           if(+this.bindNum < 0){
               msgInfoEl({
                   type:'error',
                   message:'无标签ID物资绑定数量应大于等于0',
               })
               return Promise.reject('error')
           }
        },
        checkBindNumTwo(){
            if(+this.bindNum > this.osAmount-this.getAmountSum(this.tableDataTemp)){
                msgInfoEl({
                    type:'error',
                    message:'无标签ID物资绑定数量应小于该出库单明细剩余可绑定数量',
                })
                return Promise.reject('error')
            }
        },
       async checkBindNumThree(){
            const params={
                materialCode:this.selectItem.categoryCode,
                receiveAmount:this.bindNum,
            }
           await checkMateLabelPrecision(params).then((res)=>{
                if(+res.code !== 200){
                    return Promise.reject('error')
                }
            }).catch(()=>{
                return Promise.reject('error')
            })
        },
        async checkBindNum(){
           if(this.bindNum){
               //判断大于等于0
               //判断小于等于出库数量-有签有码数量
               //校验精度是否满足条件
               await this.checkBindNumOne();
               await this.checkBindNumTwo();
               await this.checkBindNumThree();
           }
           this.$emit('save', this.multipleSelection,+this.bindNum)
           this.$emit('update:visible', false)
        },
        save() {
          //先判断是否存在无签码情况
          if(this.showNoLabel){
              //再判断填的数据数量，精度是否满足条件
              this.checkBindNum()
          }else{
              this.$emit('save', this.multipleSelection,0)
              this.$emit('update:visible', false)
          }
        },
        handleSelectionChange(val) {
            if(this.status){
              this.multipleSelection = val
            }
        },
        doSearch() {
            const params={
              ...this.form,
              prjId:this.selectItem.prjId,
              subType:this.selectItem.subType,
              assetsLabelList:this.tableData
            }
            filterAssetLabelList(params).then((res)=>{
              if(+res.code === 200){
                this.tableDataTemp=res.data;
              }else{
                return Promise.reject(res);
              }
            })
        },
        // 将弹框挂载在最外层
        dialogEl(refName) {
            const contentBody = window.top.document.body
            this.$nextTick(() => {
                const dialogModal = document.querySelector('.v-modal')
                const elBody = this.$refs[refName].$el
                dialogModal.style.zIndex = 4000
                elBody.style.zIndex = 4001
                contentBody.appendChild(elBody)
                contentBody.appendChild(dialogModal)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
